<template>
  <!-- 资产管理 -->
  <div class="table-box" v-loading="loading">
    <div style="width: 100%">
      <div style="width: 100%">
        <div
          style="
            display: flex;
            justify-content: space-between;
            padding: 10px;
            margin-bottom: 10px;
            background: #ffffff;
            border-radius: 5px;
          "
        >
          <div class="filter-box" @click="getCimByType('countAllCim')">
            <div class="num">{{ allCimCount }}</div>
            <div class="text">资产总数</div>
          </div>
          <!-- <div class="filter-box" @click="getCimByType('countAllCim')">
            <div class="num">{{ allCimCount }}</div>
            <div class="text">资产总数</div>
          </div>
          <div class="filter-box" @click="getCimByType('countAllCim')">
            <div class="num">{{ allCimCount }}</div>
            <div class="text">资产总数</div>
          </div>
          <div class="filter-box" @click="getCimByType('countAllCim')">
            <div class="num">{{ allCimCount }}</div>
            <div class="text">资产总数</div>
          </div> -->
          <div class="filter-box" @click="getCimByType(item.id)" v-for="item in countList" :key="item.id">
            <div class="num">{{ item.data }}</div>
            <div class="text">{{ item.label === "unknown" ? "未知" : item.label }}</div>
          </div>
        </div>
      </div>
      <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :data-callback="dataCallback" row-key="ciId">
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="primary" v-auth="'add'" plain @click="addAsset">添加</el-button>
          <el-button
            type="danger"
            v-auth="'delete'"
            plain
            :disabled="!scope.isSelected"
            @click="delSelectItem(scope.selectedList)"
          >
            删除
          </el-button>
          <el-button type="primary" plain @click="searchVisible = true">搜索</el-button>
          <!-- <el-button type="primary" v-auth="'export'" plain @click="exportFile">本页资产导出</el-button>
          <el-button type="primary" v-auth="'import'" plain @click="showImportMask">导入模板</el-button>    -->
        </template>
        <!-- 状态 -->
        <template #status="scope">
          <div v-if="scope.row.statusColor" :style="{ background: scope.row.statusColor }" style="color: #ffffff">
            {{ scope.row.status }}
          </div>
          <div v-else>{{ scope.row.status }}</div>
        </template>
        <template #depreciationIsZeroYears="scope">
          <div>{{ scope.row.depreciationIsZeroYears }}年</div>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" v-auth="'view'" link :icon="View" @click="openDetails(scope.row)">查看</el-button>
          <el-button type="primary" v-auth="'edit'" link :icon="EditPen" @click="editAsset(scope.row)">编辑</el-button>
          <el-button type="primary" v-auth="'delete'" link :icon="Delete" @click="deleteItem(scope.row)">删除</el-button>
        </template>
      </ProTable>
      <!-- 搜索 -->
      <el-dialog v-model="searchVisible" title="搜索" width="920">
        <el-form label-width="100">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="所属客户">
                <el-select v-model="filterForm.companyNo" clearable>
                  <el-option v-for="(item, index) in orgList" :key="index" :label="item.orgName" :value="item.orgNo"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="资产名称">
                <el-input v-model="filterForm.ciname" placeholder="请输入资产名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="资产编号">
                <el-input v-model="filterForm.cino" placeholder="请输入固定资产编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="配置项分类">
                <div style="display: flex; width: 100%">
                  <el-input
                    style="flex: 1; overflow: hidden"
                    v-model="filterForm.categoryName"
                    placeholder="请选择配置项分类"
                    :readonly="true"
                    clearable
                  ></el-input>
                  <el-button
                    style="margin-left: 10px"
                    type="primary"
                    :icon="Search"
                    @click="selectConfigItem('filterForm.categoryNo')"
                  ></el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门">
                <!-- <el-input v-model="filterForm.department" placeholder="请输入部门名称" /> -->
                <div style="display: flex; width: 100%">
                  <el-input
                    style="flex: 1; overflow: hidden"
                    v-model="filterForm.department"
                    placeholder="请选择部门"
                    :readonly="true"
                    clearable
                  ></el-input>
                  <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="selectDepartment"></el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-select v-model="filterForm.statusId" clearable>
                  <el-option v-for="(item, index) in statusList" :key="index" :label="item.dname" :value="item.dcode"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置">
                <el-tree-select
                  v-model="filterForm.locId"
                  :data="positionList"
                  check-strictly
                  :render-after-expand="false"
                  clearable
                  @change="locChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购日期">
                <el-date-picker
                  v-model="buyDate"
                  type="daterange"
                  range-separator=" - "
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="资产原值">
                <div class="flex-row">
                  <el-input type="number" v-model="filterForm.assetsOriginalValue" placeholder="请输入数字" clearable />
                  <span style="margin: 0 5px">-</span>
                  <el-input type="number" v-model="filterForm.assetsOriginalEndValue" placeholder="请输入数字" clearable />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到货日期">
                <el-date-picker
                  v-model="arrivalDate"
                  type="daterange"
                  range-separator=" - "
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预警日期">
                <el-date-picker
                  v-model="warningDate"
                  type="daterange"
                  range-separator=" - "
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生命周期(月)">
                <div class="flex-row">
                  <el-input type="number" v-model="filterForm.lifeCycle" placeholder="请输入数字" clearable />
                  <span style="margin: 0 5px">-</span>
                  <el-input type="number" v-model="filterForm.lifeEndCycle" placeholder="请输入数字" clearable />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保修期(月)">
                <div class="flex-row">
                  <el-input type="number" v-model="filterForm.warranty" placeholder="请输入数字" clearable />
                  <span style="margin: 0 5px">-</span>
                  <el-input type="number" v-model="filterForm.endWarranty" placeholder="请输入数字" clearable />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用人">
                <div style="display: flex; width: 100%">
                  <el-input
                    style="flex: 1; overflow: hidden"
                    v-model="filterForm.userName"
                    placeholder="请选择使用人"
                    :readonly="true"
                  ></el-input>
                  <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="selectUser('userName')"></el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="负责人">
                <div style="display: flex; width: 100%">
                  <el-input
                    style="flex: 1; overflow: hidden"
                    v-model="filterForm.owner"
                    placeholder="请选择负责人"
                    :readonly="true"
                  ></el-input>
                  <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="selectUser('owner')"></el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="createTime"
                  type="daterange"
                  range-separator=" - "
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="更新时间">
                <el-date-picker
                  v-model="lastUpdateTime"
                  type="daterange"
                  range-separator=" - "
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="clearSearchData">重置</el-button>
            <el-button type="primary" @click="search">搜索</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 编辑弹窗 -->
      <EditAssetMask ref="editAssetMask" @add="refreshList(true)" @change="refreshList(false)"></EditAssetMask>
      <!-- 详情弹窗 -->
      <DetailsMask ref="detailsMask"></DetailsMask>
      <!-- 导入弹窗 -->
      <el-dialog v-model="importMask" title="导入资产模板数据" width="600" :close-on-click-modal="false">
        <div>
          <el-form label-width="95">
            <el-form-item label="所属客户" required>
              <el-select v-model="importForm.companyNo" placeholder="请选择所属客户">
                <el-option v-for="item in orgList" :key="item.orgNo" :label="item.orgName" :value="item.orgNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="配置项分类" required>
              <div style="display: flex; width: 100%">
                <el-input
                  style="flex: 1; overflow: hidden"
                  v-model="categoryName"
                  placeholder="请选择配置项分类"
                  :readonly="true"
                  clearable
                ></el-input>
                <el-button
                  style="margin-left: 10px"
                  type="primary"
                  :icon="Search"
                  @click="selectConfigItem('importForm.categoryNo')"
                ></el-button>
              </div>
            </el-form-item>
            <el-form-item label="CSV文件" required>
              <div style="width: 100%">
                <el-upload
                  ref="upload"
                  class="upload-demo"
                  v-model:file-list="filesList"
                  drag
                  action="javascript:;"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :auto-upload="false"
                  accept=".csv"
                >
                  <el-icon><Plus /></el-icon>
                  <div class="el-upload__text">点击或将文件拖拽到这里上传</div>
                </el-upload>
              </div>
              <el-link type="primary" @click="downloadTempFile">[CSV模板下载]</el-link>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="importMask = false">取消</el-button>
            <el-button type="primary" @click="importFile">导入</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 选择配置项 -->
      <SelectConfigItem ref="selectConfigItemMask" @change="selectConfigItemChange"></SelectConfigItem>
      <!-- 选择部门 -->
      <SelectDepartment ref="selectDepartmentMask" @change="departmentChange"></SelectDepartment>
      <!-- 选择用户弹窗 -->
      <SelectUserMask ref="selectUserMask" @change="userChange"></SelectUserMask>
      <!-- 资产管理导出文件列表 -->
      <ExportFileList ref="exportFileList" v-if="showExportFileList"></ExportFileList>
    </div>
  </div>
</template>

<script setup lang="ts" name="assetManagement">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { User } from "@/api/interface";

import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, EditPen, View, Search } from "@element-plus/icons-vue";
import { genFileId } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from "element-plus";

import {
  cItemsFind,
  ciItemsCount,
  cItemsDel,
  exportConfigureItem,
  createTemplateWithCategory,
  importConfigureItem
} from "@/api/modules/assetManagement";

import { useUserStore } from "@/stores/modules/user";
import { allAssetOptions } from "@/stores/modules/asset";

import ProTable from "@/components/ProTable/index.vue";
import DetailsMask from "@/components/Asset/DetailsMask.vue";
import EditAssetMask from "./components/EditAssetMask.vue";
import SelectUserMask from "@/components/SelectUserMask/index.vue";
import ExportFileList from "@/components/ExportFileList/index.vue";
import SelectConfigItem from "@/components/SelectConfigItem/SelectConfigItem.vue";
import SelectDepartment from "@/components/SelectDepartment/SelectDepartment.vue";

import { useRouter } from "vue-router";
import { useAuthButtons } from "@/hooks/useAuthButtons";
// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

const userStore = useUserStore();
const assetOptions = allAssetOptions();
// const router = useRouter();

// 所属客户列表
const orgList = computed(() => {
  let list = assetOptions.orgList || [];
  let companyNo = userStore.userInfo.companyNo;
  let hasItem = false;
  list.forEach((item: any) => {
    if (item.orgNo === companyNo) {
      hasItem = true;
    }
  });
  if (!hasItem) {
    list.push({
      orgName: userStore.userInfo.companyName,
      orgNo: userStore.userInfo.companyNo
    });
  }
  return list;
});
//资产统计
const allCimCount = ref(0);
const countList = ref<any[]>([]);
const getCiItemsCount = async () => {
  const params = {
    "ciQueryDTO.groupField": "status",
    "ciQueryDTO.loginName": userStore.username
  };
  const res = (await ciItemsCount(params)) as any;
  console.log(res);
  countList.value = res;
  res.forEach((item: any) => {
    allCimCount.value += item.data;
  });
};
const cimId = ref<any>();
const isCim = ref(false);
const getCimByType = (type: any) => {
  cimId.value = type;
  isCim.value = true;
  refreshList(true);
};

// 状态列表
const statusList = computed(() => {
  return assetOptions.statusList || [];
});

// 位置列表
const positionList = computed(() => {
  let list: any[] = JSON.parse(JSON.stringify(assetOptions.positionList));
  list.forEach((item: any) => {
    item.label = item.attr.cname;
    item.value = item.attr.id;
    if (item.children.length > 0) {
      item.children.forEach((vo: any) => {
        vo.label = vo.attr.cname;
        vo.value = vo.attr.id;
      });
    }
  });
  return list;
});

onMounted(() => {
  assetOptions.getAllOptions();
  getCiItemsCount();
});

// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "ciId", label: "ID", fixed: "left", width: 90 },
  { prop: "companyName", label: "所属客户", width: 160 },
  { prop: "categoryName", label: "配置项分类", width: 160 },
  { prop: "cino", label: "固定资产编号", width: 160 },
  { prop: "ciname", label: "资产名称", width: 160 },
  { prop: "status", label: "状态", width: 120 },
  { prop: "loc", label: "位置", width: 140 },
  { prop: "userName", label: "使用人", width: 150 },
  { prop: "createTime", label: "创建时间", width: 170 },
  { prop: "lastUpdateTime", label: "更新时间", width: 170 },
  { prop: "depreciationIsZeroYears", label: "折旧年限", width: 120 },
  { prop: "operation", label: "操作", fixed: "right", width: 240 }
]);

// ProTable 实例
const proTable = ref<ProTableInstance>();
const loading = ref(false);
const isRefresh = ref(false);

const filterForm = reactive({
  companyNo: "", // 所属部门
  ciname: "", // 资产名称
  cino: "", // 资产编号
  categoryNo: "", // 分类
  categoryName: "",
  department: "", // 部门
  statusId: "", // 状态
  locId: "", // 位置id
  loc: "", // 位置中文
  buyDate: "", // 采购日期
  buyEndDate: "",
  assetsOriginalValue: "", // 资产原值
  assetsOriginalEndValue: "",
  arrivalDate: "", // 到货日期
  arrivalEndDate: "",
  warningDate: "", // 预警日期
  warningEndDate: "",
  lifeCycle: "", // 生命周期
  lifeEndCycle: "",
  warranty: "", // 保修期
  endWarranty: "",
  userName: "", // 使用人
  owner: "", // 负责人
  createTime: "", // 创建时间
  createTimeEnd: "",
  lastUpdateTime: "", // 更新时间
  lastUpdateTimeEnd: ""
});

// 查询树中的某项
const findEmployeeById = (arr: any[], value: any) => {
  for (let item of arr) {
    if (item.value) {
      if (item.value === value) {
        return item;
      }
    } else if (item.id) {
      if (item.id === value) {
        return item;
      }
    }
    if (item.children && Array.isArray(item.children)) {
      const result = findEmployeeById(item.children, value);
      if (result) {
        return result;
      }
    }
  }
  return null;
};

const locChange = e => {
  let data = findEmployeeById(positionList.value, e);
  filterForm.loc = data.label;
};

// 选择配置项
const selectConfigItemMask = ref();
const selectConfigItemType = ref("");
const selectConfigItem = type => {
  selectConfigItemType.value = type;
  selectConfigItemMask.value?.open();
};
const categoryName = ref("");
const selectConfigItemChange = e => {
  switch (selectConfigItemType.value) {
    case "filterForm.categoryNo":
      filterForm.categoryNo = e.cno;
      filterForm.categoryName = e.cname;
      break;
    case "importForm.categoryNo":
      importForm.categoryNo = e.cno;
      categoryName.value = e.cname;
      break;

    default:
      break;
  }
};

// 选择部门
const selectDepartmentMask = ref();
// 打开选择部门弹窗
const selectDepartment = () => {
  selectDepartmentMask.value?.open();
};
const departmentChange = (e: any) => {
  filterForm.department = e.orgName;
};

// 采购日期
const buyDate = ref([]);
watch(
  () => buyDate.value,
  val => {
    if (val && val.length == 2) {
      filterForm.buyDate = val[0];
      filterForm.buyEndDate = val[1];
    } else {
      filterForm.buyDate = "";
      filterForm.buyEndDate = "";
    }
  }
);

// 到货日期
const arrivalDate = ref([]);
watch(
  () => arrivalDate.value,
  val => {
    if (val && val.length == 2) {
      filterForm.arrivalDate = val[0];
      filterForm.arrivalEndDate = val[1];
    } else {
      filterForm.arrivalDate = "";
      filterForm.arrivalEndDate = "";
    }
  }
);

// 预警日期
const warningDate = ref([]);
watch(
  () => warningDate.value,
  val => {
    if (val && val.length == 2) {
      filterForm.warningDate = val[0];
      filterForm.warningEndDate = val[1];
    } else {
      filterForm.warningDate = "";
      filterForm.warningEndDate = "";
    }
  }
);

// 创建时间
const createTime = ref([]);
watch(
  () => createTime.value,
  val => {
    if (val && val.length == 2) {
      filterForm.createTime = val[0];
      filterForm.createTimeEnd = val[1];
    } else {
      filterForm.createTime = "";
      filterForm.createTimeEnd = "";
    }
  }
);

// 更新时间
const lastUpdateTime = ref([]);
watch(
  () => lastUpdateTime.value,
  val => {
    if (val && val.length == 2) {
      filterForm.lastUpdateTime = val[0];
      filterForm.lastUpdateTimeEnd = val[1];
    } else {
      filterForm.lastUpdateTime = "";
      filterForm.lastUpdateTimeEnd = "";
    }
  }
);

// 选择用户
const selectUserMask = ref();
const selectUserType = ref("");
// 打开选择用户弹窗
const selectUser = (type: string) => {
  selectUserType.value = type;
  selectUserMask.value.open();
};
// 选择了用户
const userChange = e => {
  // filterForm[selectUserType.value] = e.userId;
  filterForm[selectUserType.value] = e.fullName;
};

// 重置搜索条件
const clearSearchData = () => {
  for (const key in filterForm) {
    filterForm[key] = "";
  }
  buyDate.value = [];
  arrivalDate.value = [];
  warningDate.value = [];
};

const form = reactive({
  companyNo: "",
  ciname: "",
  cino: "",
  categoryNo: "",
  categoryName: "",
  department: "",
  statusId: "",
  locId: "",
  loc: "",
  buyDate: "",
  buyEndDate: "",
  assetsOriginalValue: "",
  assetsOriginalEndValue: "",
  arrivalDate: "", // 到货日期
  arrivalEndDate: "",
  warningDate: "", // 预警日期
  warningEndDate: "",
  lifeCycle: "", // 生命周期
  lifeEndCycle: "",
  warranty: "", // 保修期
  endWarranty: "",
  userName: "", // 使用人
  owner: "", // 负责人
  createTime: "", // 创建时间
  createTimeEnd: "",
  lastUpdateTime: "", // 更新时间
  lastUpdateTimeEnd: ""
});

const searchVisible = ref(false);
const search = () => {
  for (const key in form) {
    form[key] = filterForm[key];
  }
  searchVisible.value = false;
  refreshList(true);
};

const exportFileData = ref<any>({});

// 如果你想在请求之前对当前请求参数做一些操作
const getTableList = (params: any) => {
  loading.value = true;
  let page = params.pageNum;
  if (isRefresh.value) {
    page = 1;
    isRefresh.value = false;
  }
  let txt = "ciQueryDTO.loginName=" + userStore.username;
  let data = {
    _search: false,
    nd: new Date().getTime(),
    sidx: "ciId",
    sord: "desc",
    page: page,
    rows: params.pageSize
  };
  for (const key in form) {
    data["ciQueryDTO." + key] = form[key];
  }
  exportFileData.value = {
    ...data
  };
  if (isCim.value) {
    if (cimId.value === "countAllCim") {
      return cItemsFind(txt, data).catch(() => {
        loading.value = false;
      });
    } else {
      const statusParams = {
        "ciQueryDTO.statusId": cimId.value,
        _search: false,
        nd: new Date().getTime(),
        sidx: "ciId",
        sord: "desc",
        page: page,
        rows: params.pageSize
      };
      return cItemsFind(txt, statusParams).catch(() => {
        loading.value = false;
      });
    }
  } else {
    return cItemsFind(txt, data).catch(() => {
      loading.value = false;
    });
  }
};

const refreshList = (refresh: boolean) => {
  isRefresh.value = refresh;
  proTable.value?.getTableList();
};

// dataCallback 是对于返回的表格数据做处理
const dataCallback = (data: any) => {
  loading.value = false;
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

// 资产导出（按分页导出）
const exportFileList = ref();
const showExportFileList = ref(false);
const exportFile = () => {
  showExportFileList.value = false;
  loading.value = true;
  exportConfigureItem({
    ...exportFileData.value,
    "ciQueryDTO.loginName": userStore.username,
    nd: new Date().getTime()
  })
    .then(res => {
      loading.value = false;
      showExportFileList.value = true;
      setTimeout(() => {
        exportFileList.value?.open();
      }, 150);
    })
    .catch(() => {
      loading.value = false;
    });
};

// 导入弹窗
const importMask = ref(false);
const importForm = reactive({
  companyNo: "",
  categoryNo: ""
});
const importLoading = ref(false);
// 显示导入弹窗
const showImportMask = () => {
  importForm.companyNo = "";
  importForm.categoryNo = "";
  categoryName.value = "";
  importMask.value = true;
};
// 下载导入模板
const downloadTempFile = () => {
  if (!importForm.categoryNo) {
    ElMessage.warning("请选择配置项分类");
    return false;
  }
  importLoading.value = true;
  createTemplateWithCategory(importForm.categoryNo)
    .then((res: any) => {
      importLoading.value = false;
      const link = document.createElement("a"); // 创建一个 <a> 标签
      link.href = URL.createObjectURL(res); // 设置下载链接
      link.download = "导入模板.csv"; // 设置下载文件名
      link.target = "_blank"; // 阻止a标签默认的导航行为
      document.body.appendChild(link); // 将 <a> 标签添加到页面中
      link.click(); // 模拟点击下载
      document.body.removeChild(link); // 下载完成后移除 <a> 标签
    })
    .catch(() => {
      importLoading.value = false;
    });
};

// 导入文件列表
const filesList = ref<UploadUserFile[]>([]);
// 导入
const upload = ref<UploadInstance>();
// 选择文件
const handleExceed: UploadProps["onExceed"] = files => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

// 确定导入
const importFile = () => {
  if (!importForm.companyNo) {
    ElMessage.warning("请选择所属客户");
    return false;
  }
  if (!importForm.categoryNo) {
    ElMessage.warning("请选择配置项分类");
    return false;
  }
  if (filesList.value.length == 0) {
    ElMessage.warning("请上传文件");
    return false;
  }
  let text = `ciDto.companyNo=${importForm.companyNo}&ciDto.categoryNo=${importForm.categoryNo}`;
  let params = new FormData();
  if (filesList.value[0].raw) {
    params.append("importFile", filesList.value[0].raw);
  }
  importLoading.value = true;
  importConfigureItem(text, params)
    .then(() => {
      importLoading.value = false;
      ElMessage.success("导入成功");
      importMask.value = false;
      proTable.value?.getTableList();
    })
    .catch(() => {
      importLoading.value = false;
    });
};

// 添加资产
const addAsset = () => {
  editAssetMask.value.open(false);
};

// 编辑
const editAssetMask = ref();
const editAsset = (item: any) => {
  editAssetMask.value.open(item);
};

// 批量删除
const delSelectItem = (list: any[]) => {
  let ids = list.map((item: { ciId: any }) => {
    return item.ciId;
  });
  ElMessageBox.confirm("确定要删除选中项？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      loading.value = true;
      let txt = ids.map(item => {
        return "ids=" + item;
      });
      cItemsDel(txt.join("&"), {
        ids: ids
      })
        .then(() => {
          loading.value = false;
          ElMessage.success("删除成功");
          proTable.value?.clearSelection();
          proTable.value?.getTableList();
        })
        .catch(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // cancel operation
    });
};

// 删除
const deleteItem = (item: { ciId: string }) => {
  ElMessageBox.confirm("确定要删除该资产？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      loading.value = true;
      let txt = "ids=" + item.ciId;
      cItemsDel(txt, {
        ids: [item.ciId]
      })
        .then(() => {
          loading.value = false;
          ElMessage.success("删除成功");
          // 刷新列表
          proTable.value?.getTableList();
        })
        .catch(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 点击取消
    });
};

// 查看详情
const detailsMask = ref();
const openDetails = (item: any) => {
  detailsMask.value.open(item);
};
</script>

<style lang="scss" scoped>
.details-box {
  overflow: hidden;
  table {
    width: 100%;
    border-collapse: collapse;
  }
  table,
  th,
  td {
    border: 1px solid #e5e5e5;
  }
  th {
    width: 120px;
    padding: 5px;
  }
  td {
    padding: 5px;
  }
}
.flex-row {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.filter-box {
  box-sizing: border-box;
  width: 19%;
  padding: 15px 0 18px;
  margin-top: 10px;
  text-align: center;
  cursor: pointer;
  background-color: var(--el-menu-active-bg-color);
  background-size: 100% 100%;
  border-radius: 10px;
  transition: all 0.3s;
  .num {
    font-size: 20px;
    font-weight: bold;
    color: var(--el-color-primary);
  }
  .text {
    margin-top: 5px;
    font-size: 14px;
  }
}
</style>
